package com.project.template.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.template.entity.Cart;
import com.project.template.entity.Product;
import com.project.template.entity.Productorder;
import com.project.template.entity.UserOrder;
import com.project.template.mapper.CartMapper;
import com.project.template.mapper.UserOrderMapper;
import com.project.template.service.ProductService;
import com.project.template.service.ProductorderService;
import com.project.template.service.UserOrderService;
import com.project.template.utils.Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, UserOrder> implements UserOrderService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private ProductorderService productorderService;

    @Resource
    private ProductService productService;

    /**
     * 创建订单
     */
    @Override
    public void addOrder(UserOrder order) {
        // 设置默认值
        if (order.getUid() == null) {
            order.setUid(Utils.getUser().getId());
        }
        if (order.getOnumber() == null || order.getOnumber().isEmpty()) {
            order.setOnumber(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        if (order.getOtime() == null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setOtime(dateFormat.format(new Date()));
        }
        if (order.getOtype() == null) {
            order.setOtype("自取"); // 默认状态为自取
        }
        if (order.getPaystate() == null) {
            order.setPaystate("已支付"); // 默认支付状态为已支付
        }
        if (order.getOstate() == null) {
            order.setOstate("未收货"); // 订单状态为未收货
        }
        // 设置备注信息
        if (order.getRemark() == null) {
            order.setRemark(""); // 如果没有备注，默认为空字符串
        }

        //1、根据用户id,获取目前购物车信息
        Integer userId = order.getUid();

        //查询购物车中的商品信息 当前用户
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUid, userId);
        List<Cart> carts = cartMapper.selectList(wrapper);

        // 计算总价
        double totalPrice = 0.0;
        for (int i = 0; i < carts.size(); i++) {
            Cart cart = carts.get(i);
            totalPrice += cart.getNumber() * cart.getTprice();
        }
        order.setOprice(totalPrice); // 总价

        //2、生成订单
        save(order);

        //3、生成产品、订单中间表，通过流水号来进行关联
        createProductOrder(carts, order.getOnumber());

        //4、删除购物车中的数据
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUid, userId);
        cartMapper.selectList(queryWrapper).forEach(v -> {
            cartMapper.deleteById(v.getId());
        });
    }

    /**
     * 根据不用的订单状态来查询结果
     *
     * @param ostate
     * @return
     */
    @Override
    public List<UserOrder> queryOrder(String ostate) {

        //多张表查询，只能用多表联查来做吗？
        Integer userId = Utils.getUser().getId();

        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserOrder::getUid, userId);
        //没有传入值就查全部
        if (!"".equals(ostate)) {
            wrapper.eq(UserOrder::getOstate, ostate);
        }

        //根据uid和ostate查询值
        List<UserOrder> orders = list(wrapper);
        orders.forEach(v -> {
            LambdaQueryWrapper<Productorder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Productorder::getOid, v.getOnumber());
            List<Product> arrayList = new ArrayList<>();
            for (Productorder productorder : productorderService.list(queryWrapper)) {
                arrayList.add(productService.getById(productorder.getPid()));
            }
            v.setProduct(arrayList);

        });

        return orders;
    }

    @Override
    public List<UserOrder> queryInfo(String paystate) {

        //多张表查询，只能用多表联查来做吗？
        Integer userId = Utils.getUser().getId();

        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserOrder::getUid, userId);
        //没有传入值就查全部
        if (!"".equals(paystate)) {
            wrapper.eq(UserOrder::getPaystate, paystate);
        }

        //根据uid和ostate查询值
        List<UserOrder> orders = list(wrapper);
        orders.forEach(v -> {
            LambdaQueryWrapper<Productorder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Productorder::getOid, v.getOnumber());
            List<Product> arrayList = new ArrayList<>();
            for (Productorder productorder : productorderService.list(queryWrapper)) {
                arrayList.add(productService.getById(productorder.getPid()));
            }
            v.setProduct(arrayList);

        });

        return orders;
    }






    /**
     * 订单中间表
     * @param carts
     * @param uuid
     */
    private void createProductOrder(List<Cart> carts, String uuid) {
        List<Productorder> list = new ArrayList<>();
        for (int i = 0; i < carts.size(); i++) {
            Cart cart = carts.get(i);
            Productorder productorder = new Productorder();
            productorder.setNumber(cart.getNumber());
            productorder.setOid(uuid);
            productorder.setPid(cart.getPid());
            productorder.setPrice(cart.getTprice());
            list.add(productorder);

        }
        productorderService.saveBatch(list);
    }

    @Override
    public UserOrder queryorder(String onumber) {
        // 查询订单信息
        List<UserOrder> userOrders = list(new LambdaQueryWrapper<UserOrder>().eq(UserOrder::getOnumber, onumber));
        if (userOrders == null || userOrders.isEmpty()) {
            return null;
        }

        UserOrder userOrder = userOrders.get(0);

        // 查询商品信息
        List<Product> products = queryProduct(onumber);
        userOrder.setProduct(products);

        return userOrder;
    }

    public List<Product> queryProduct(String onumber) {
        // 创建查询条件
        LambdaQueryWrapper<Productorder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Productorder::getOid, onumber);

        // 查询产品订单信息
        List<Productorder> productOrderList = productorderService.list(queryWrapper);

        // 根据产品订单信息查询对应的产品信息
        List<Product> productList = new ArrayList<>();
        for (Productorder productOrder : productOrderList) {
            Product product = productService.getById(productOrder.getPid());
            productList.add(product);
        }

        return productList;
    }
}
